 package org.edu.modules.pub.controller;
 import com.github.xiaoymin.knife4j.annotations.ApiSort;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;

 import java.io.*;
 import java.math.BigInteger;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.shiro.SecurityUtils;
 import org.edu.common.api.vo.Result;
 import org.edu.common.aspect.annotation.AutoLog;
 import org.edu.common.system.api.ISysBaseAPI;
 import org.edu.common.system.vo.LoginUser;
 import org.edu.common.util.CommonUtils;
 import org.edu.common.util.TimeStampUtil;
 import org.edu.common.util.oConvertUtils;
 import org.edu.modules.pub.entity.UpFileInfo;
 import org.edu.modules.pub.entity.VeFileFiles;
 import org.edu.modules.pub.entity.VeFileImage;
 import org.edu.modules.pub.service.IVeFileFilesService;
 import org.edu.modules.pub.service.IVeFileImageService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.util.AntPathMatcher;
 import org.springframework.util.FileCopyUtils;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.servlet.HandlerMapping;

 @Api(tags = {"文件服务"})
 @RestController
 @RequestMapping({"/pub/file"})
 @ApiSort(0)
 public class FileController {
/*  47 */   private static final Logger log = LoggerFactory.getLogger(org.edu.modules.pub.controller.FileController.class);


   @Autowired
   private ISysBaseAPI sysBaseAPI;


   @Autowired
   private IVeFileImageService veFileImageService;


   @Autowired
   private IVeFileFilesService veFileFilesService;

   @Value("${edu.path.upload}")
   private String uploadpath;

   @Value("${edu.uploadType}")
   private String uploadType;

   @Value("${edu.path.urlPre}")
   private String fileUrlPre;


   @GetMapping({"/403"})
   public Result<?> noauth() {
     return Result.error("没有权限，请联系管理员授权");
   }




   public Result<?> upload(@RequestParam("file") MultipartFile file) {
     Result<?> result = new Result();
     UpFileInfo upFileInfo = uploadLocal(file);
     if (upFileInfo == null) {
      result.setMessage("上传失败！");
       result.setSuccess(false);
     } else {

       result = Result.OK("上传成功！", upFileInfo);
     }
     return result;
   }

   @AutoLog("公用功能-上传图片")
   @ApiOperation(value = "上传保存到image表", notes = "公用功能-上传图片")
   @PostMapping({"/uploadImage"})
   public Result<?> uploadImage(@RequestParam("file") MultipartFile file) {
     Result<?> result = new Result();
     UpFileInfo upFileInfo = uploadLocal(file);
    if (upFileInfo == null) {
       result.setMessage("上传失败！");
       result.setSuccess(false);
       return result;
     }
     VeFileImage veFileImage = new VeFileImage();
     String url = upFileInfo.getPath();
     veFileImage.setSourcefile(url);
     veFileImage.setSize(upFileInfo.getSize());
     veFileImage.setExt(url.substring(url.lastIndexOf(".") + 1));
     veFileImage.setName(file.getOriginalFilename());
     veFileImage.setSha1(upFileInfo.getSha1());
    veFileImage.setCreatetime(TimeStampUtil.getNowSecondStamp());
    LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
     int userId = (sysUser != null) ? Integer.valueOf(sysUser.getUserId()) : 0;
    veFileImage.setCreateuser(Integer.valueOf(userId));
     veFileImage.setPlaceId(Integer.valueOf(1));
     if (this.veFileImageService.save(veFileImage)) {
       upFileInfo.setId(veFileImage.getId().intValue());
       upFileInfo.setPath(this.fileUrlPre + upFileInfo.getPath());
       result = Result.OK("上传成功！", upFileInfo);
       return result;
     }
     return Result.error("保存文件表失败!");
   }
   @AutoLog("公用功能-上传文件")
   @ApiOperation(value = "上传保存到files表", notes = "公用功能-上传文件")
   @PostMapping({"/uploadFile"})
   public Result<?> uploadFiles(@RequestParam("file") MultipartFile file) {
     Result<?> result = new Result();
     UpFileInfo upFileInfo = uploadLocal(file);
     if (upFileInfo == null) {
       result.setMessage("上传失败！");
       result.setSuccess(false);
       return result;
     }
     VeFileFiles veFileFiles = new VeFileFiles();
     String url = upFileInfo.getPath();
     veFileFiles.setSourcefile(url);
     veFileFiles.setSize(upFileInfo.getSize());
     veFileFiles.setExt(url.substring(url.lastIndexOf(".") + 1));
     veFileFiles.setName(file.getOriginalFilename());
     veFileFiles.setSha1(upFileInfo.getSha1());
     veFileFiles.setMd5(upFileInfo.getMd5());
     veFileFiles.setCoverfile("");
     veFileFiles.setLength(Integer.valueOf(0));
     veFileFiles.setCreatetime(TimeStampUtil.getNowSecondStamp());
     LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
     int userId = (sysUser != null) ? Integer.valueOf(sysUser.getUserId()) : 0;
     veFileFiles.setCreateuser(Integer.valueOf(userId));
     veFileFiles.setPlaceId(Integer.valueOf(1));
     if (this.veFileFilesService.save(veFileFiles)) {
       upFileInfo.setId(veFileFiles.getId().intValue());
       upFileInfo.setPath(this.fileUrlPre + upFileInfo.getPath());
       result = Result.OK("上传成功！", upFileInfo);
       return result;
     }
     return Result.error("保存文件表失败!");
   }







   private UpFileInfo uploadLocal(MultipartFile mf) {
     UpFileInfo upFileInfo = null;
     SimpleDateFormat df = new SimpleDateFormat("yyyyMM/dd");
     String datePath = df.format(new Date());
     String bizPath = "upFiles/" + datePath;

     try {
       String ctxPath = this.uploadpath;
       String fileName = null;
       File file = new File(ctxPath + File.separator + bizPath + File.separator);
       if (!file.exists()) {
         file.mkdirs();
       }
       String orgName = mf.getOriginalFilename();
       orgName = CommonUtils.getFileName(orgName);
       if (orgName.indexOf(".") != -1) {
         fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
       } else {
         fileName = orgName + "_" + System.currentTimeMillis();
       }
       String savePath = file.getPath() + File.separator + fileName;
       File savefile = new File(savePath);
       FileCopyUtils.copy(mf.getBytes(), savefile);
       String dbpath = null;
       if (oConvertUtils.isNotEmpty(bizPath)) {
         dbpath = bizPath + File.separator + fileName;
       } else {
         dbpath = fileName;
       }
       if (dbpath.contains("\\")) {
         dbpath = dbpath.replace("\\", "/");
       }
       if (oConvertUtils.isNotEmpty(dbpath)) {
         upFileInfo = new UpFileInfo();
         upFileInfo.setPath(dbpath);
         upFileInfo.setSize(mf.getSize());
         upFileInfo.setMd5(getFileMD5(savefile));
         upFileInfo.setSha1(getFileSha1(savefile));
       }

     } catch (IOException e) {
       log.error(e.getMessage(), e);
     }

     return upFileInfo;
   }







   private static String extractPathFromPattern(HttpServletRequest request) {
     String path = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
     String bestMatchPattern = (String)request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
     return (new AntPathMatcher()).extractPathWithinPattern(bestMatchPattern, path);
   }



   public static String getFileSha1(File file) {
     FileInputStream in = null;

     try {
/* 229 */       in = new FileInputStream(file);
/* 230 */       MessageDigest digest = MessageDigest.getInstance("SHA-1");
/* 231 */       byte[] buffer = new byte[10485760];

/* 233 */       int len = 0;
/* 234 */       while ((len = in.read(buffer)) > 0)
       {
/* 236 */         digest.update(buffer, 0, len);
       }
/* 238 */       String sha1 = (new BigInteger(1, digest.digest())).toString(16);
/* 239 */       int length = 40 - sha1.length();
/* 240 */       if (length > 0)
       {
/* 242 */         for (int i = 0; i < length; i++)
         {
/* 244 */           sha1 = "0" + sha1;
         }
       }
/* 247 */       return sha1;
     }
/* 249 */     catch (IOException e) {

/* 251 */       System.out.println(e);
     }
/* 253 */     catch (NoSuchAlgorithmException e) {

/* 255 */       System.out.println(e);
     } finally {


       try {

/* 261 */         if (in != null)
         {
/* 263 */           in.close();
         }
       }
/* 266 */       catch (IOException e) {

/* 268 */         System.out.println(e);
       }
     }
/* 271 */     return null;
   }


   public static String getFileMD5(File file) {
/* 276 */     FileInputStream in = null;

     try {
/* 279 */       in = new FileInputStream(file);
/* 280 */       MessageDigest digest = MessageDigest.getInstance("MD5");
/* 281 */       byte[] buffer = new byte[10485760];

/* 283 */       int len = 0;
/* 284 */       while ((len = in.read(buffer)) > 0)
       {
/* 286 */         digest.update(buffer, 0, len);
       }
/* 288 */       String md5 = (new BigInteger(1, digest.digest())).toString(16);
/* 289 */       int length = 32 - md5.length();
/* 290 */       if (length > 0)
       {
/* 292 */         for (int i = 0; i < length; i++)
         {
/* 294 */           md5 = "0" + md5;
         }
       }
/* 297 */       return md5;
     }
/* 299 */     catch (IOException e) {

/* 301 */       System.out.println(e);
     }
/* 303 */     catch (NoSuchAlgorithmException e) {

/* 305 */       System.out.println(e);
     } finally {


       try {

/* 311 */         if (in != null)
         {
/* 313 */           in.close();
         }
       }
/* 316 */       catch (IOException e) {

/* 318 */         System.out.println(e);
       }
     }
/* 321 */     return null;
   }









   @GetMapping({"/download/**"})
   public void view(HttpServletRequest request, HttpServletResponse response) {
     ServletOutputStream servletOutputStream = null;
/* 335 */     String imgPath = extractPathFromPattern(request);
/* 336 */     if (oConvertUtils.isEmpty(imgPath) || imgPath == "null") {
       return;
     }

/* 340 */     InputStream inputStream = null;
/* 341 */     OutputStream outputStream = null;
     try {
/* 343 */       imgPath = imgPath.replace("..", "");
/* 344 */       if (imgPath.endsWith(",")) {
/* 345 */         imgPath = imgPath.substring(0, imgPath.length() - 1);
       }
/* 347 */       String filePath = this.uploadpath + File.separator + imgPath;
/* 348 */       File file = new File(filePath);
/* 349 */       if (!file.exists()) {
/* 350 */         response.setStatus(404);
/* 351 */         throw new RuntimeException("文件不存在..");
       }
/* 353 */       response.setContentType("application/force-download");
/* 354 */       response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
/* 355 */       inputStream = new BufferedInputStream(new FileInputStream(filePath));
/* 356 */       servletOutputStream = response.getOutputStream();
/* 357 */       byte[] buf = new byte[1024];
       int len;
/* 359 */       while ((len = inputStream.read(buf)) > 0) {
/* 360 */         servletOutputStream.write(buf, 0, len);
       }
/* 362 */       response.flushBuffer();
/* 363 */     } catch (IOException e) {
/* 364 */       log.error("预览文件失败" + e.getMessage());
/* 365 */       response.setStatus(404);
/* 366 */       e.printStackTrace();
     } finally {
/* 368 */       if (inputStream != null) {
         try {
/* 370 */           inputStream.close();
/* 371 */         } catch (IOException e) {
/* 372 */           log.error(e.getMessage(), e);
         }
       }
/* 375 */       if (servletOutputStream != null)
         try {
/* 377 */           servletOutputStream.close();
/* 378 */         } catch (IOException e) {
/* 379 */           log.error(e.getMessage(), e);
         }
     }
   }
 }


